import React from 'react';
import { DragDropContext, Draggable, Droppable } from 'react-beautiful-dnd';
import { noop } from '../../../../utils/utils';
import { CommonTable } from '../CommonTable';
const Row = ({ id, index, record, ...restProps }) => {
    return (<Draggable key={id} draggableId={id} index={index}>
      {(provided) => (<tr key={id} ref={provided.innerRef} {...restProps} {...provided.draggableProps} {...provided.dragHandleProps}/>)}
    </Draggable>);
};
const Wrapper = (props) => {
    return (<Droppable droppableId="droppable">
      {(provided) => (<>
          <tbody ref={provided.innerRef} {...props} {...provided.droppableProps}>
          </tbody>
          <tfoot>
            {provided.placeholder}
          </tfoot>
        </>)}
    </Droppable>);
};
/**
 * 支持行级拖拽的table，不支持嵌套数据拖拽
*/
export const DragTable = React.memo((props) => {
    const { rowKey, onBeforeCapture = noop, onBeforeDragStart = noop, onDragStart = noop, onDragUpdate = noop, onDragEnd = noop, value = [], onValueChange, ...args } = props;
    const handleDragEnd = (result, provided) => {
        const { destination, source, draggableId } = result;
        if (!destination) {
            return;
        }
        if (destination.index === source.index) {
            return;
        }
        const newTableData = value.slice();
        // removing the item
        newTableData.splice(source.index, 1);
        // pushing in the new position
        newTableData.splice(destination.index, 0, value.find(el => el[rowKey] === draggableId));
        onValueChange?.(newTableData);
        onDragEnd?.(result, provided);
    };
    return (<DragDropContext onBeforeCapture={onBeforeCapture} onBeforeDragStart={onBeforeDragStart} onDragStart={onDragStart} onDragUpdate={onDragUpdate} onDragEnd={handleDragEnd}>
      <CommonTable components={{
            body: {
                wrapper: Wrapper,
                row: Row
            }
        }} onRow={((record, index) => ({
            index,
            record,
            id: record[rowKey],
        }))} rowKey={rowKey} value={value} onValueChange={onValueChange} {...args}/>
    </DragDropContext>);
});
export default DragTable;
